package club.banyuan.hrms.servlet;

import club.banyuan.hrms.domain.Admin;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class AuthenticateFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        if (req instanceof HttpServletRequest) {
            HttpServletRequest request = (HttpServletRequest) req;

            // 如果是登录页面，无需过滤
            String uri = request.getRequestURI();
            if (uri.endsWith(".jpg") || uri.endsWith(".js") || uri.endsWith(".css")) {
                chain.doFilter(request, resp);
                return;
            }

            if (!uri.contains("login")) {
                // 判断用户是否登录
                if (!isLogin(request)) {
                    HttpServletResponse response = (HttpServletResponse) resp;
                    response.sendRedirect(request.getContextPath() + "/login.jsp");
                    return;
                }
            }

        }
        chain.doFilter(req, resp);
    }

    private boolean isLogin(HttpServletRequest request) {
        // 登录信息在session中，先取session
        HttpSession session = request.getSession();

        // session的account属性表明登录用户
        Admin account = (Admin) session.getAttribute("account");
        return account != null;
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
